package com.ruoyi.common.utils;


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;

/**
 * 功能说明: 对象转换工具<br>
 * 系统版本: v1.0<br>
 * 开发人员: @author Mr.Wen<br>
 * 开发时间: 2019-6-3<br>
 */
public class ObjectUtil {

	public static Map<String, Object> toMap(Object obj) {
		Map<String, Object> reMap = new HashMap<String, Object>();
		if (obj == null) {
			return reMap;
		}
		Field[] fields = obj.getClass().getDeclaredFields();
		try {
			for (int i = 0; i < fields.length; i++) {
				try {
					Field f = obj.getClass().getDeclaredField(fields[i].getName());
					f.setAccessible(true);
					Object o = f.get(obj);
					reMap.put(fields[i].getName(), o);
				} catch (NoSuchFieldException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return reMap;
	}


	/***
	 * 对集合进行深拷贝 注意需要对泛型类进行序列化(实现Serializable)
	 *
	 * @param srcList
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> depCopy(List<T> srcList) {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		try {
			ObjectOutputStream out = new ObjectOutputStream(byteOut);
			out.writeObject(srcList);
			ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
			ObjectInputStream inStream = new ObjectInputStream(byteIn);
			List<T> destList = (List<T>) inStream.readObject();
			return destList;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

    /**
     * 两个对象中相同的属性值复制
     * @param source
     * @param dest
     * @throws Exception
     */
    public static void copyProperties(Object source, Object dest) {
        try{
            //获取属性
            BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), Object.class);
            PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
            BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), Object.class);
            PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
            for(int i=0;i<sourceProperty.length;i++){
                for(int j=0;j<destProperty.length;j++){
                    if(sourceProperty[i].getName().equals(destProperty[j].getName())){
                        if (sourceProperty[i].getReadMethod().invoke(source) != null) {
                            destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
                        }
                        break;
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}